# -*- coding: utf-8 -*-
"""
@FileName：bubbles_sys.py
@Description：气泡管理，创建，删除，位置更新
@Author：锦沐Python
@Time：2024/8/17 16:26
"""

import pygame
import random


class Bubble:
    """
    气泡对象，定义常用属性
    """

    def __init__(self, start_radius, start_center_pos):
        # 注意 参数 start_radius 是指释放气泡的范围半径
        # 气泡半径
        self.radius = random.randint(3, start_radius // 4)
        pos_x = random.randint(start_center_pos[0] - start_radius, start_center_pos[0] + start_radius)
        pos_y = random.randint(start_center_pos[1] + self.radius, start_center_pos[1] + 2 * self.radius)
        # 气泡移动方向向量
        self.direct = pygame.math.Vector2(pos_x, pos_y)
        # 气泡范围
        self.rect = pygame.Rect(pos_x - self.radius, pos_y - self.radius, self.radius * 2, self.radius * 2)
        # 气泡步长，用于控制速度
        self.step = pygame.math.Vector2(random.randint(1, 4), random.randint(1, 3))


class BubblesSys:
    """
    管理所有气泡，创建气泡，销毁气泡
    """

    def __init__(self, screen=None, max_num=10, start_center_pos=(600, 400), start_radius=300):
        self.screen = screen
        # 气泡数量
        self.max_num = max_num
        # 释放气泡的中心位置
        self.start_center_pos = start_center_pos
        # 释放气泡距离中心位置的距离
        self.start_radius = start_radius
        # 气泡位置信息
        self.bubbles_list = []

        for _ in range(random.randint(3, self.max_num)):
            self.create_bubble()

    def create_bubble(self):
        """
        创建新的气泡
        """
        # music_sys.play_bubble(True)
        bubble = Bubble(self.start_radius, self.start_center_pos)
        self.bubbles_list.append(bubble)

    def crash_window(self, bubble):
        """
        检查气泡是否超出窗口，超出销毁
        :param bubble:
        """
        bubble_rect = bubble.rect
        window_rect = self.screen.get_rect()
        if bubble_rect.right < -self.start_radius // 2 \
                or bubble_rect.left > window_rect.width \
                or bubble_rect.bottom < -self.start_radius // 2:
            # print(bubble)
            self.bubbles_list.remove(bubble)

    def update(self):
        """
        更新气泡位置
        """
        # 判断释放达到数量上线
        if len(self.bubbles_list) < self.max_num // 2:
            self.create_bubble()

        # 更新所有气泡位置信息
        for bubble in self.bubbles_list:
            self.crash_window(bubble)
            pygame.draw.circle(self.screen, (255, 255, 255), bubble.rect.center, bubble.radius, 1)

            bubble.direct = bubble.direct - bubble.step

            bubble.rect.center = (bubble.direct.x, bubble.direct.y)
